<template>
  <el-drawer
    size="100%"
    v-model="dialogVisibled"
    :before-close="handleClose"
    :with-header="false"
    :close-on-click-modal="false"
    @open="handleDialogOpen"
  >
    <el-tabs
      v-model="activeName"
      @tab-click="handleClick"
      style="margin-left: 10px; min-width: 1440px"
    >
      <el-tab-pane label="基本信息" name="baseMsg">
        <el-form
          ref="ruleFormRef"
          :model="flowApprovalModel"
          status-icon
          :rules="rules"
          label-width="auto"
        >
          <el-form-item label="标题：" prop="ApplyTitle">
            <el-input
              v-model="flowApprovalModel.ApplyTitle"
              placeholder="请输入标题"
              maxlength="20"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="加急指数：" prop="UrgentIndex">
            <el-rate v-model="flowApprovalModel.UrgentIndex" />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input
              v-model="flowApprovalModel.Remark"
              maxlength="300"
              placeholder="请输入备注"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="表单信息" name="formMsg">
        <v-form-render :form-json="formJson" ref="vfDesigner" :key="updateKey">
        </v-form-render>
      </el-tab-pane>
      <el-tab-pane label="流程图" name="flowMsg">
        <dawnFlow
          :NodeBar="true"
          :ToolBar="true"
          :isPreview="true"
          ref="uploadFileRef"
          style="width: 100%; min-height: 800px; overflow: auto"
        />
        <div class="opt-style-text1" style="top: 50px;">
          <div style="margin-top: 2px; cursor: pointer">
            <div class="nodeTagStyle inExamineBackColor"></div>
            待审核
            <div class="nodeTagStyle agreeBackColor"></div>
            已通过
            <div class="nodeTagStyle disagreeBackColor"></div>
            不同意
            <div class="nodeTagStyle rejectBackColor"></div>
            驳回
          </div>
          <div style="margin-left: 10px">
            <el-button type="primary" link @click="downloadClick"
              ><el-icon size="18"><Picture /></el-icon>导出图片</el-button
            >
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- <div class="custom-divider-bottom"></div> -->
    <template #footer>
      <el-button icon="Close" size="large" type="danger" plain @click="handleClose"
        >取消</el-button
      >
      <el-button type="primary" size="large" icon="Check" plain @click="submitForm"
        >保存节点</el-button
      >
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { GetFlowOrFormByFlowId } from "@/api/flow";
import { InsertFlowApply } from "@/api/flowApply";
import {
  ElMessage,
  FormInstance,
  FormRules,
  MessageParamsWithType,
  TabsPaneContext,
} from "element-plus";
import { computed, nextTick, reactive, ref } from "vue";
const props = defineProps({
  isVisibles: { type: Boolean, required: true },
  dialogTitle: { type: String, required: true },
  flowId: { type: String, required: true },
});
const emit = defineEmits(["closeBnt", "saveNodeClick"]);

const activeName = ref("baseMsg");
const formJson = ref<any>();
const updateKey = ref(0);
//流程ref
const uploadFileRef = ref();
//表单ref
const vfDesigner = ref();
//流程申请数据
const flowApprovalModel = reactive({
  FormData: "",
  FlowId: "",
  ApplyTitle: "",
  UrgentIndex: 1,
  Remark: "",
});

//打开时加载
const handleDialogOpen = function () {
  updateKey.value = 0;
  formJson.value = [];
  activeName.value = "baseMsg";
  flowApprovalModel.ApplyTitle = "";
  flowApprovalModel.Remark = "";
  flowApprovalModel.UrgentIndex = 1;
  flowApprovalModel.FormData='';
  resetForm(ruleFormRef.value);
  uploadFileRef.value.delFlowClick();
  getFlowOrFormByFlowIdMsg();
};

//根据流程id获取流程和表单数据
const getFlowOrFormByFlowIdMsg = function () {
  GetFlowOrFormByFlowId({ flowId: props.flowId }).then(({ data, code }) => {
    if (code == 200) {
      nextTick(() => {
        formJson.value = JSON.parse(data.FormJson);
        uploadFileRef.value.setFlowJson(data.FlowContent);
        updateKey.value++;
      });
    }
  });
};

//导出图片
const downloadClick = function () {
  uploadFileRef.value.downloadImageClick();
};

//#region  验证规则

//注册验证
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<typeof flowApprovalModel>>({
  ApplyTitle: [
    {
      required: true,
      message: "请填标题!",
      trigger: "blur",
    },
  ],
  UrgentIndex: [
    {
      required: true,
      message: "请选择加急指数!",
      trigger: "blur",
    },
  ],
});
//清除验证
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
//验证表单基本信息
const verifyFormBaseMsg = async (formEl: FormInstance | undefined) => {
  var isTrue = ref<boolean>();
  if (!formEl) return;
  await formEl.validate((valid) => {
    isTrue.value = valid;
  });
  return isTrue;
};
//#endregion

//提交
const submitForm = async () => {
  const formBaseState = await verifyFormBaseMsg(ruleFormRef.value);
  if (formBaseState?.value) {
    await vfDesigner.value
      .getFormData(true)
      .then((formData: any) => {
        flowApprovalModel.FormData = JSON.stringify(formData);
      })
      .catch((_error: MessageParamsWithType) => {
       activeName.value = "formMsg";
        ElMessage.error("请完善表单信息");
      });
    flowApprovalModel.FlowId = props.flowId;
    if (flowApprovalModel.FormData != "") {
      InsertFlowApply(flowApprovalModel).then(({ code }) => {
        if (code == 200) {
          ElMessage.success("申请成功");
          handleClose();
        }
      });
    }
  }
};

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

//是否显示dialog
const dialogVisibled = computed(() => {
  return props.isVisibles;
});
//关闭事件
const handleClose = () => {
  emit("closeBnt");
  // resetForm(ruleFormRef.value);
};
</script>

<style scoped>
.dialog-header-center {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}
</style>
